using System;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using MedicalReportAssistant.Services;
using MedicalReportAssistant.Controllers;
using MedicalReportAssistant.Views;
using System.IO;

namespace MedicalReportAssistant
{
    public partial class App : Application
    {
        private ServiceProvider _serviceProvider;

        public App()
        {
            var services = new ServiceCollection();
            ConfigureServices(services);
            _serviceProvider = services.BuildServiceProvider();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // 全局异常捕获
            AppDomain.CurrentDomain.UnhandledException += (s, ex) =>
            {
                MessageBox.Show($"未处理异常: {((Exception)ex.ExceptionObject).Message}\n\n{((Exception)ex.ExceptionObject).StackTrace}", "全局异常", MessageBoxButton.OK, MessageBoxImage.Error);
            };
            this.DispatcherUnhandledException += (s, ex) =>
            {
                MessageBox.Show($"UI线程异常: {ex.Exception.Message}\n\n{ex.Exception.StackTrace}", "UI异常", MessageBoxButton.OK, MessageBoxImage.Error);
                ex.Handled = true;
            };

            // 检查配置文件是否存在
            var configPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
            if (!File.Exists(configPath))
            {
                MessageBox.Show($"配置文件 appsettings.json 不存在！\n请确保配置文件在项目根目录下。", "配置文件缺失", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown();
                return;
            }

            try
            {
                // 构建配置
                var configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddEnvironmentVariables()
                    .Build();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"配置文件格式错误或内容无效！\n{ex.Message}", "配置文件错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown();
                return;
            }

            var mainWindow = _serviceProvider.GetRequiredService<FloatingWindow>();
            mainWindow.Show();
        }

        private void ConfigureServices(IServiceCollection services)
        {
            // 添加配置
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            services.AddSingleton<IConfiguration>(configuration);

            // 配置日志
            services.AddLogging(builder =>
            {
                builder.AddDebug();
                builder.AddConsole();
                builder.SetMinimumLevel(LogLevel.Debug); // 设置最低日志级别
            });

            // 配置HTTP客户端
            services.AddHttpClient();

            // 注册服务
            services.AddSingleton<IOCRService, TesseractOCRService>();
            services.AddSingleton<IDeepSeekService, DeepSeekService>();
            services.AddSingleton<IKnowledgeBaseService, LocalKnowledgeBaseService>();
            services.AddSingleton<MedicalReportController>();

            // 注册窗口（改为Transient，确保每次都创建新实例）
            services.AddTransient<FloatingWindow>();
            services.AddTransient<LogWindow>();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            _serviceProvider?.Dispose();
            base.OnExit(e);
        }
    }
} 